package com.ml4ai.backend.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Base64;

public class ObjUtil {

    private static Base64.Encoder encoder = Base64.getEncoder();
    private static Base64.Decoder decoder = Base64.getDecoder();

    public static String obj2str(Object object) throws Exception {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream o = new ObjectOutputStream(baos);
            o.writeObject(object);
            o.flush();
            byte[] data = baos.toByteArray();
            String str = encoder.encodeToString(data);
            CloseUtils.close(baos);
            CloseUtils.close(o);
            return str;
        } catch (Throwable anyException) {
            throw new Exception((Exception) anyException);
        }
    }

    public static <T> T str2obj(String str) throws Exception {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(decoder.decode(str));
            ObjectInputStream oi = new ObjectInputStream(bais);
            Object obj = oi.readObject();
            CloseUtils.close(bais);
            CloseUtils.close(oi);
            return (T) obj;
        } catch (Exception any) {
            throw any;
        }
    }

}
